package com.hmdp.utils;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{
    private String  name ;
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }


    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    private static final String  KEY_PREFIX = "lock";
    private static final String  ID_PREFIX = UUID.randomUUID().toString()+"-";

    @Override
    public boolean  tryLock(long timeoutSec){
//        以防队伍阻塞   集群模式   因此   使用UUID作为   某个集群标识
          String  threadId = ID_PREFIX+Thread.currentThread().getId();
       Boolean bool =  stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name,threadId,timeoutSec, TimeUnit.SECONDS);
            return Boolean.TRUE.equals(bool);
//                    返回boolean时自动拆箱   数据可能会错误 比如Boolean的null  因此要
      }
      @Override
      public void unlock() {
          // 调用lua脚本
          stringRedisTemplate.execute(
                  UNLOCK_SCRIPT,
                  Collections.singletonList(KEY_PREFIX + name),
                  ID_PREFIX + Thread.currentThread().getId());
      }
//    经过以上代码改造后，我们就能够实现 拿锁比锁删锁的原子性动作了~

//    public void unlock(){
//          String  threadId = ID_PREFIX+Thread.currentThread().getId();
//          String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
//          if (threadId.equals(id)){
//              stringRedisTemplate.opsForValue().getOperations().delete(KEY_PREFIX+name);
//          }
//      }
}
